/**
 * 
 */
package com.estock.web.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.estock.config.xml.TaskDefs;
import org.quartz.CronExpression;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.estock.common.model.task.Task;
import com.estock.common.util.support.ESLogger;
import com.estock.platform.http.utils.RequestUtil;
import com.estock.web.service.TaskService;

/**
 * @author richard
 * 
 */
@Controller
public class TaskController {

	protected final ESLogger logger = ESLogger.getLogger(TaskController.class);
	
	@Resource
	TaskService taskService; 

	public TaskService getTaskService() {
		return taskService;
	}
	
	
	//////// Return View

	//////// Return Json
	
	@RequestMapping(value="findAllTasks.es", method = RequestMethod.GET)
	@ResponseBody
	public List<Task> findAllTasks() throws Exception {
		logger.info("start finding all tasks.");
		
		return getTaskService().findAllTasks();
	}
	
	@RequestMapping(value="saveOrUpdateTask.es", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public Task saveOrUpdateTask(@RequestBody Task task) throws Exception {
		logger.info("start saveOrUpdate task.");
		return getTaskService().saveOrUpdateTask(task);
	}
	
	@RequestMapping(value="deleteTask.es", method = RequestMethod.POST)
	@ResponseBody
	public String deleteTask(@RequestBody Task task) throws Exception {
		logger.info("start delete task.");
		getTaskService().deleteTask(task);
		return "success";
	}
	
	@RequestMapping(value="getNextValidTime.es", method = RequestMethod.GET)
	@ResponseBody
	public Date getNextValidTime(@RequestParam String cronExpression) throws Exception {
		logger.info("start getNextValidTime with param:" + cronExpression);
		
		Date now = new Date();
        CronExpression cron = new CronExpression(RequestUtil.decode(cronExpression, "UTF-8"));
        Date nextSDTime = cron.getNextValidTimeAfter(now);
		return nextSDTime;
	}
	
	@RequestMapping(value="loadTaskDefs.es", method = RequestMethod.GET)
	@ResponseBody
	public List<Task> loadTaskDefs() throws Exception {
		logger.info("start loading task defs.");
		return TaskDefs.getTaskdefs();
	}

}
